package CommentApi.Util;

import com.sun.javadoc.RootDoc;

import java.io.File;
import java.util.*;

public class JavaDocLetUtil {
    private static RootDoc rootDoc;
    private JavaDocLetUtil(){}
    public static boolean start(RootDoc rootDoc){
        JavaDocLetUtil.rootDoc = rootDoc;
        return true;
    }

    private static void execute(String[] args){
        com.sun.tools.javadoc.Main.execute(args);
    }

    private static RootDoc getRootDoc(){
        return Optional.ofNullable(rootDoc).orElseThrow(()->new RuntimeException("未初始化"));
    }

    /**
     *  读取文件下所有.java文件
     * @param controllerPagePath controller所在文件夹(其实可以适用所有文件夹)的地址
     * @return 构造的根实例
     */
    public static RootDoc generateControllersRootDoc(String controllerPagePath){
        List<String> args = new ArrayList<>();
        args.add("-doclet");
        args.add(JavaDocLetUtil.class.getName());
        final ArrayList<String> list = new ArrayList<>();
        final File file = new File(controllerPagePath);
        final Queue<File> deque = new ArrayDeque<>();
        deque.offer(file);
        while (!deque.isEmpty()){
            final File poll = deque.poll();
            if (poll.isDirectory()){
                final File[] files = poll.listFiles(f -> f.isDirectory() || f.getName().endsWith(".java"));
                for (File file1 : files) {
                    deque.offer(file1);
                }
            }else {
                list.add(poll.toString());
            }
        }
        args.addAll(list);
        execute(args.toArray(new String[args.size()]));
        return JavaDocLetUtil.getRootDoc();
    }

}

